// 简单实现一个 promise 雏形
function Promise(fn) {
  var value = null,
    state = 'pending',
    callbacks = []; // 回调函数数组

  this.then = function (onFufilled, onRejected) {
    return new Promise(function (resolve) {
      handle({
        onFufilled: onFufilled || null,
        onRejected: onRejected || null,
        resolve: resolve,
        reject: reject
      })
    })
  }

  function handle (callback) {
    if(state === 'pending') {
      callbacks.push(callback);
      return;
    }
    var cb = state === 'fulfilled' ? callback.onFufilled : callback.onRejected,
      ret;
    if(cb === null) {
      cb = state === 'fulfilled' ? callback.resolve : callback.reject;
      cb(value);
      return;
    }
    ret = cb(value);
    callback.resolve(ret);
  }

  function reject (reason) {
    state = 'rejected';
    value = reason;
    execute();
  }
  function execute() {
    setTimeout(function () {
      callbacks.forEach(function (callback) {
        handle(callback);
      }, 0);
    })
  }

  function resolve(newValue) {
    if(newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
      var then = newValue.then;
      if(typeof then === 'function') {
        then.call(newValue, resolve, reject);
        return;
      }
    }
    value = newValue;
    state = 'fulfilled';
    setTimeout(function() {
      callbacks.forEach(function (callback) {
        handle(callback);
      })
    }, 0);
  }

  fn(resolve, reject);
}

// 模拟异步
function asyncPromise() {
  return new Promise(function (resolve) {
    setTimeout(function () {
      console.log('hello');
      resolve('world');
    }, 1000);
  })
}
function asyncPromise1() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log('hello-1');
      resolve('world-1');
    }, 1000);
  })
}

var promise = asyncPromise().then(function (value) {
  console.log(value);
  return value
}).then(asyncPromise1)

// setTimeout(function () {
//   promise.then(function(value) {
//     console.log(value);
//   })
// }, 2000);